<template>
    <div class="message-container" ref="messageContainer">
        <MessageArea title="留言板" :subTitle="`(${data.total})`" :isListLoading="isLoading" :list="data.rows"
            @submit="handleSubmit" />
    </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import fetchData from "@/mixins/fetchData";
import * as msgApi from "@/api/message";
import mainScroll from "@/mixins/mainScroll";
export default {
    components: { MessageArea },
    mixins: [fetchData({ total: 0, rows: [] }), mainScroll("messageContainer")],
    data() {
        return {
            page: 1,
            limit: 10,
        }
    },
    computed: {
        hasMore() {
            return this.data.rows.length < this.data.total
        }
    },
    methods: {
        async fetchData() {
            return await msgApi.getMessages(this.page, this.limit)
        },
        async handleSubmit(data, callback) {
            const resp = await msgApi.postMessages(data);
            callback("感谢您的留言");
            data.rows.unshift(resp)
        },
        handlerScroll(dom) {
            if (this.isLoading || !dom) {
                //目前正在加载更多
                return;
            }
            const range = 100; //误差范围,范围内都算到达底部
            const dec = Math.abs((dom.scrollTop + dom.clientHeight) - dom.scrollHeight);
            if (dec <= range) {
                this.fetchMore();
            }
        },
        async fetchMore() {
            if (!this.hasMore) {
                //没有更多的数据了
                return;
            }
            this.isLoading = true;
            this.page++;
            const resp = await this.fetchData();
            this.data.total = resp.total;
            this.data.rows = this.data.rows.concat(resp.rows);
            this.isLoading = false;
        },
    },
    created() {
        this.$bus.$on("mainScroll", this.handlerScroll)
    },
    destroy() {
        this.$bus.$off("mainScroll", this.handlerScroll)
    },
}
</script>

<style scoped lang="less">
.message-container {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    padding: 25px 0;
    box-sizing: border-box;
    scroll-behavior: smooth;
}

.message-area-container {
    width: 700px;
    margin: 0 auto;
}
</style>